package tuding.android.bigplanettracks.tudingConnection;


import java.io.File;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.Map;

import tuding.android.bigplanettracks.BigPlanet;
import tuding.android.bigplanettracks.R;
import tuding.android.bigplanettracks.imageupload.ImageUploaderActivity;
import tuding.android.bigplanettracks.maps.Logex;
import tuding.android.bigplanettracks.maps.storage.SQLLocalStorage;
import tuding.android.bigplanettracks.maps.tuding.InfoWindow;
import tuding.android.bigplanettracks.tracks.writer.GpxTrackWriterEx;
import tuding.android.bigplanettracks.util.Preferences;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.Location;
import android.os.Handler;
import android.os.Message;
//import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
//import android.widget.AdapterView;
//import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
//import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.AdapterView.OnItemSelectedListener;

public class UploadLocation {
	
	private Context context;
	private Location clocation;
	private ProgressDialog pdialog;
	private Handler viewhandler;
	public final static int NEED_LOGIN = 109;
	public final static int UNKNOWN_ERROR = 107;
	public final static int UPLOAD_INTERRUPTED = 106;
	public final static int UPLOAD_DONE_WITH_SUCCESS = 100;
	private static final String LOGIN_SUCCESS_TEXT = "uploaddonesuccess";
	private static String imguristr = "";
	private static String imgdesc = "";
	private static String anotes = "";
	
	public UploadLocation(Context context, Handler handler) {
		this.context = context;
		this.clocation = null;
		this.viewhandler = handler;
	}
	
	
	public void uploadLocationSimple(Location loc) {
		if(Preferences.isLogined()) {
			clocation = loc;
			myThread mt = new myThread();
			mt.setName("upload location thread");
            mt.start();
		} else {
			showRcDialog(NEED_LOGIN);
		}
	}
	
	// rc: 0: success
	//     1: 
	//     9: need login first
	public void uploadLocation(Location loc) {
		if(Preferences.isLogined()) {
			clocation = loc;
			addActions();
		} else {
			showRcDialog(NEED_LOGIN);
		}
	}
	
	public void setImgUriStr(String uristring) {
		imguristr = uristring;
	}
	public void resetImgUriStr() {
		imguristr = "";
	}
	
	public void setImgDesc(String photodesc) {
		imgdesc = photodesc;
	}
	public void resetImgDesc() {
		imgdesc = "";
	}
	public void setNotes(String notes) {
		anotes = notes;
	}
	public void resetNotes() {
		anotes = "";
	}
	
	private void addImage() {
	    Intent intent = new Intent(context,ImageUploaderActivity.class); 
	    //intent.putExtra(BigPlanet.PRIVACY_SETTING, true);
	    Activity act =(Activity)context;
	    act.startActivityForResult(intent, BigPlanet.ActionPhotoUploadingWithLoc);
	}

	
	private void addActions() {
	    final Dialog dl = new Dialog(context);
        View v = View.inflate(context, R.layout.uploadlocation, null);
        Logex.message("UPLOAD", "imguristr is "+imguristr+" imgdesc "+imgdesc);
        
        if(imguristr != "") { // there is a photo
        	ImageView iv = (ImageView) v.findViewById(R.id.uploadlocation_photopreview);
        	Bitmap smallphoto = InfoWindow.getBitmapFromLocalPath(SQLLocalStorage.TRACK_PATH+"photo/thumbnail/thumbnail"+imguristr, 1);
        	//Bitmap smallphoto = InfoWindow.getBitmapFromLocalPath(SQLLocalStorage.TRACK_PATH+"photo/"+imguristr, 2);
        	//Log.i("UPLOAD", ""+smallphoto+" "+SQLLocalStorage.TRACK_PATH+"photo/thumbnail/thumbnail"+imguristr);
			iv.setImageBitmap(smallphoto);
			if(imgdesc != "") {
				TextView tvpd = (TextView) v.findViewById(R.id.uploadlocation_takephoto);
				tvpd.setText(context.getString(R.string.PREVIEW)+": "+imgdesc);
				Logex.message("UPLOAD", context.getString(R.string.PREVIEW)+": "+imgdesc);
			}
        	ImageButton btn = (ImageButton) v.findViewById(R.id.uploadlocation_addphotobtn);
			btn.setVisibility(View.GONE);
        }
        if(anotes != "") {
        	TextView tv = (TextView) v.findViewById(R.id.uploadlocation_notesvalue);
        	tv.setText(anotes);
        }
        
        ImageButton updateImgBtn = (ImageButton) v.findViewById(R.id.uploadlocation_addphotobtn);
        updateImgBtn.setEnabled(true);
        updateImgBtn.setClickable(false);
        updateImgBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
            	if(dl != null)dl.dismiss();
            	addImage();
            }
        });
        
        
        final TextView tv = (TextView) v.findViewById(R.id.uploadlocation_notesvalue);
        
        
        /*final Spinner spinner = (Spinner) v.findViewById(R.id.uploadlocation_spinner);
        ArrayAdapter<CharSequence> adapter =  ArrayAdapter.createFromResource(context, R.array.location_privacy, android.R.layout.simple_spinner_item); 
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        spinner.setSelection(Preferences.getTudingUploadPrivacy());
        spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {
                int tudingUploadPrivacy = spinner.getSelectedItemPosition();
                if(tudingUploadPrivacy >=0 && tudingUploadPrivacy<=2) 
                    Preferences.setTudingUploadPrivacy(tudingUploadPrivacy);
            }
            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub
                
            }
        }); */  
        
        final Button confirmBtn = (Button) v.findViewById(R.id.confirmTudingBtn);
        confirmBtn.setEnabled(true);
        confirmBtn.setClickable(false);
        confirmBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
                anotes = tv.getText().toString();
                if(dl != null)dl.dismiss(); // should not disapped until return with success
                final myThread mt = new myThread();
                // show Progress Dialog
                pdialog = ProgressDialog.show(
                        context,
                        context.getString(R.string.UPLOAD_LOCATION),
                        "",
                        true,
                        true,
                        new DialogInterface.OnCancelListener() {
                            public void onCancel(DialogInterface dialog) {
                                mt.stopped = true;
                            }
                        }
                );
                mt.setName("upload location thread");
                mt.start();
            }
        });
        
        final Button cancelBtn = (Button) v.findViewById(R.id.cancelTudingBtn);
        cancelBtn.setEnabled(true);
        cancelBtn.setClickable(false);
        cancelBtn.setOnClickListener(new OnClickListener() {

            public void onClick(View arg0) {
            	resetImgDesc();
				resetImgUriStr();
				resetNotes();
				if(dl != null)dl.dismiss();
            }
        });
        
        
        dl.setTitle(R.string.UPDATE_MYLOCATION);
        dl.setCanceledOnTouchOutside(false);
        dl.setCancelable(true);
        dl.setContentView(v);
        dl.show();
        
	}
	
	private void showRcDialog(int rc) {
		Logex.message("CONN", "showRC: "+rc);
		switch(rc){
		case NEED_LOGIN:
			Toast.makeText(context, context.getString(R.string.NEED_LOGIN),	Toast.LENGTH_LONG).show();
			break;
		case UPLOAD_INTERRUPTED:
			Toast.makeText(context, context.getString(R.string.UPLOAD_INTERRUPTED),	Toast.LENGTH_LONG).show();
			break;
		case UNKNOWN_ERROR:
			Toast.makeText(context, context.getString(R.string.unknown_error)+" !",	Toast.LENGTH_LONG).show();
			break;
		case UPLOAD_DONE_WITH_SUCCESS:
			Toast.makeText(context, context.getString(R.string.SUBMIT_SUCCESS),	Toast.LENGTH_LONG).show();
			break;
		default:
			Toast.makeText(context, context.getString(R.string.unknown_error),	Toast.LENGTH_LONG).show();
			break;
		}
	}
	
	
	class myThread extends Thread {
		
		public boolean stopped = true;

		public void run() {
			
			stopped = false;

			try{
				Logex.message("CONN", "Connecting ...");
				Map<String, String> params = new HashMap<String, String>();
				params.put("do", "updatelocation"); // 
				params.put("notes", anotes); 
				int tmp = Preferences.getTudingUploadPrivacy();
				if(tmp == 2) tmp = 3; // 2 is reserver for only part of friend
				params.put("priv", ""+tmp); // 
				params.put("username", Preferences.getUsername());
				params.put("password", Preferences.getPassword());
				params.put("lat", ""+clocation.getLatitude());
				params.put("lon", ""+clocation.getLongitude());
				params.put("acc", ""+clocation.getAccuracy());
				params.put("alt", ""+clocation.getAltitude());
				
				// set the photo 
				Map<String, File> files = new HashMap<String, File>();
				if(imguristr != "") {
					files.put(imguristr, new File(SQLLocalStorage.TRACK_PATH+"photo/"+imguristr));
					if(imgdesc != "") {
						params.put("imgdesc", imgdesc);
					}
				}
				
				Logex.message("CONN", "lat: "+params.get("lat")+" lon: "+params.get("lon")+" username: "+Preferences.getUsername()+" pw: "+Preferences.getPassword()+" priv: "+Preferences.getTudingUploadPrivacy());
				//Log.i("CONN", "Notes: "+anotes);

				String postUrl = BigPlanet.SERVER_ADDRESS+"gmap_uploadlocation.php";

				String rc = "";
				if(files.size()>0) {
					//Log.i("UPLOAD", "file size is not 0");
					rc = BaseConnection.postToTuding(postUrl, params, files);
				} else {
					rc = BaseConnection.postToTuding(postUrl, params, null);
				}

				//Log.i("CONN", "RC:"+rc);
				Message msg = new Message();
				if (stopped) {
					Logex.message("CONN", "Thread stopped.");
					msg.what = UPLOAD_INTERRUPTED;
					viewhandler.sendMessage(msg);
				} else if (!rc.contains(LOGIN_SUCCESS_TEXT)) {
					Logex.message("CONN", "Unknown return error with stopped");
					msg.what = UNKNOWN_ERROR;
					viewhandler.sendMessage(msg);
				} else {
					Logex.message("CONN", "submit successfully!");
					msg.what = UPLOAD_DONE_WITH_SUCCESS; 
					resetImgDesc();
					resetImgUriStr();
					resetNotes();
					viewhandler.sendMessage(msg);
				}

			} catch(SocketException e) { 
				Message msg = new Message();
				msg.what = GpxTrackWriterEx.SOCKETEXCEPTION;
				viewhandler.sendMessage(msg);
				Logex.message("UPLOAD", "Exception happened with message: "+e.getMessage());
				e.printStackTrace();
			} catch(SocketTimeoutException  e) {
				Message msg = new Message();
				msg.what = GpxTrackWriterEx.UPLOAD_DATA_TIMEOUT;
				viewhandler.sendMessage(msg);
				e.printStackTrace();
			} catch(Exception e) {
				Message msg = new Message();
				msg.what = UNKNOWN_ERROR;
				viewhandler.sendMessage(msg);
				e.printStackTrace();
			} finally {
				if(pdialog != null)	pdialog.dismiss();
			}
		}// end of run
	}

}